package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.constant.CacheNames;
import com.ruoyi.common.core.constant.WorkOrderConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.redis.utils.CacheUtils;
import com.ruoyi.common.satoken.utils.LoginHelper;
import com.ruoyi.system.domain.HnWorkOrderAction;
import com.ruoyi.system.domain.bo.HnWorkOrderActionBo;
import com.ruoyi.system.domain.vo.HnWorkOrderActionVo;
import com.ruoyi.system.mapper.HnWorkOrderActionMapper;
import com.ruoyi.system.service.IHnWorkOrderActionService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.HnWorkOrderBo;
import com.ruoyi.system.domain.vo.HnWorkOrderVo;
import com.ruoyi.system.domain.HnWorkOrder;
import com.ruoyi.system.mapper.HnWorkOrderMapper;
import com.ruoyi.system.service.IHnWorkOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 工单对象Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-08
 */
@RequiredArgsConstructor
@Service
public class HnWorkOrderServiceImpl implements IHnWorkOrderService {

    private final HnWorkOrderMapper baseMapper;

    private final IHnWorkOrderActionService workOrderActionService;

    private final HnWorkOrderActionMapper workOrderActionMapper;

    /**
     * 查询工单对象
     */
    @Override
    public HnWorkOrderVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Cacheable(cacheNames = CacheNames.HN_WORK_ORDER_NAME, key = "#id")
    public String selectNameById(String id){
        LambdaQueryWrapper<HnWorkOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(HnWorkOrder::getName)
            .eq(HnWorkOrder::getId,id);
        HnWorkOrder workOrder = baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(workOrder)){
            return workOrder.getName();
        }
        return null;
    }

    @Override
    public String
    selectNameByIds(String ids) {
        String[] idsList = ids.split(",");
        List<String> names = new ArrayList<>();
        for (int i = 0; i < idsList.length; i++) {
            String id = idsList[i];
            String name = this.selectNameById(id);
            if (ObjectUtil.isNotEmpty(name)){
                names.add(name);
            }
        }
        return StringUtils.join(names,",");
    }

    /**
     * 处理工单
     * @param bo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public HnWorkOrderActionVo processing(HnWorkOrderActionBo bo) {
        //1、根据工单id查询工单
        HnWorkOrder hnWorkOrder = baseMapper.selectById(bo.getWorkId());
        //2、根据传入的状态，看看是否需要更改工单状态
        if (ObjectUtil.isNotEmpty(bo.getStatus()) && !bo.getStatus().equals(WorkOrderConstants.CONFIRMED_COMPLETION) && !bo.getStatus().equals(WorkOrderConstants.processed)){
            hnWorkOrder.setStatus(WorkOrderConstants.PROCESSING);
            baseMapper.updateById(hnWorkOrder);
        }
        //3、插入工单处理记录
        Long userId = LoginHelper.getUserId();
        HnWorkOrderAction workOrderAction = workOrderActionService.createWorkOrderAction(hnWorkOrder, userId);
        workOrderActionMapper.insert(workOrderAction);
        //4、查询返回
        HnWorkOrderActionVo hnWorkOrderActionVo = workOrderActionService.queryById(workOrderAction.getId());
        return hnWorkOrderActionVo;
    }

    /**
     * 查询工单对象列表
     */
    @Override
    public TableDataInfo<HnWorkOrderVo> queryPageList(HnWorkOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HnWorkOrder> lqw = buildQueryWrapper(bo);
        Page<HnWorkOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询工单对象列表
     */
    @Override
    public List<HnWorkOrderVo> queryList(HnWorkOrderBo bo) {
        LambdaQueryWrapper<HnWorkOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HnWorkOrder> buildQueryWrapper(HnWorkOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HnWorkOrder> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), HnWorkOrder::getName, bo.getName());
        lqw.eq(bo.getDeptId() != null, HnWorkOrder::getDeptId, bo.getDeptId());
        lqw.eq(bo.getStatus() != null, HnWorkOrder::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getInfo()), HnWorkOrder::getInfo, bo.getInfo());
        lqw.eq(bo.getAssignedUserId() != null, HnWorkOrder::getAssignedUserId, bo.getAssignedUserId());
        lqw.eq(bo.getTroubleshootUserId() != null, HnWorkOrder::getTroubleshootUserId, bo.getTroubleshootUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getOssIds()), HnWorkOrder::getOssIds, bo.getOssIds());
        lqw.eq(bo.getCompletionTime() != null, HnWorkOrder::getCompletionTime, bo.getCompletionTime());
        lqw.eq(StringUtils.isNotBlank(bo.getElapsedTime()), HnWorkOrder::getElapsedTime, bo.getElapsedTime());
        return lqw;
    }

    /**
     * 新增工单对象
     */
    @Override
    public Boolean insertByBo(HnWorkOrderBo bo) {
        HnWorkOrder add = BeanUtil.toBean(bo, HnWorkOrder.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改工单对象
     */
    @CacheEvict(cacheNames = CacheNames.HN_WORK_ORDER_NAME,key = "#bo.id")
    @Override
    public Boolean updateByBo(HnWorkOrderBo bo) {
        HnWorkOrder update = BeanUtil.toBean(bo, HnWorkOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HnWorkOrder entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除工单对象
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        this.clearCache(ids);
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    private void clearCache(Collection<Long> ids){
        for (Long id : ids) {
            CacheUtils.evict(CacheNames.HN_WORK_ORDER_NAME,id);
        }
    }
}
